import ProLayout from '@ant-design/pro-layout';
import React, { useEffect, useState, useMemo } from 'react';
import { connect } from 'dva';
// import Authorized from '@/utils/Authorized';
import { Link, router } from 'umi';
import { Tabs, Button, Icon } from 'antd';
import { MenuFoldOutlined, MenuUnfoldOutlined } from '@ant-design/icons';
import { getPageItemByPath, getPageItemById, getParentMenuByPage } from '@/utils/utils';
import styles from './SubNavLayout.less';
import KeepAlive, { useAliveController } from 'react-activation'

const menuDataRender = menuList => {
  return menuList && menuList.length && menuList.map(
    item => ({ ...item, children: item.children ? menuDataRender(item.children) : [] }),
    // return Authorized.check(item.authority, localItem, null);
  );
};

// 在本tag页面内跳转
const doNotRoute = [
  "/banksearchSystem/inPortBaggageManagement/addEditIncident",
  "/banksearchSystem/inPortBaggageManagement/addEditIncidentMore",
  "/banksearchSystem/inPortBaggageManagement/accidentDetail",
  "/banksearchSystem/inPortBaggageManagement/accidentDetailMore",
  "/banksearchSystem/inPortBaggageManagement/addEditCompensation",
  "/banksearchSystem/inPortBaggageManagement/compensationDetail",
  "/banksearchSystem/inPortBaggageManagement/printPage",
  "/banksearchSystem/inPortBaggageManagement/printPeiChang",
  "/banksearchSystem/quickRetrieval",
  "/banksearchSystem/outPortBaggageManagement/addEditIncident",
  "/banksearchSystem/outPortBaggageManagement/incidentDetail",
  "/banksearchSystem/outPortBaggageManagement/incidentDetail",
  "/banksearchSystem/lostItemManage/lostItemForm",
  "/banksearchSystem/outPortBaggageManagement/printPage",
  "/banksearchSystem/lostItemManage/printPage",
];

const SubNavLayout = props => {
  const { children, location, menuData, changeCancelOrKeep } = props;
  const [tags, setTags] = useState(props.auditDetail.tags);
  const { dropScope } = useAliveController();
  const [currentTag, setCurrentTag] = useState({});
  const [currentSubMenu, setCurrentSubMenu] = useState({});

  useEffect(() => {
    props.dispatch({
      type: 'auditDetail/changeTabs',
      payload: {
        tags,
        setTags,
        cleartag: [],
      }
    })
  }, [tags, setTags]);
  // 设置dva中过滤之后的tabs
  useEffect(() => {
    // setTags(props.auditDetail.tags)
    tagOptions.removeTag(props.auditDetail?.cleartag[0]?.id, 'pageClose');
  }, [children, tagOptions]);

  const tagOptions = useMemo(
    () => ({
      removeTag: (id, type) => {
        if (currentTag.id === id) {
          // 点击close图标，清除"航延服务申请单"缓存数据
          if (currentTag.path?.indexOf('usualMonitor/AuditDetail') >= 0) {
            props.dispatch({
              type: 'auditDetail/resetUploadList'
            });
          }
          // 点击tab的关闭图表，才回退到上一个tab
          if (type === 'iconClose') {
            const nextIndex = [].findIndex.call(tags, item => item.id === id) - 1;
            tagOptions.clickTag(tags[nextIndex < 0 ? 1 : nextIndex]?.id);
          }
          // 解决关闭后重新打开的问题
          setTimeout(() => {
            setTags(tags => tags.filter(item => item.id !== id));
            // 解除已经关闭的tab页面的缓存
            dropScope(currentTag.path);
          }, 0);
        } else {
          // 不在当前页面点击关闭,清除缓存
          let removeTagObj = tags.filter(item => item.id === id)
          dropScope(removeTagObj[0]?.path);
          setTags(tags => tags.filter(item => item.id !== id)); // 问题：id为空
        }
      },
      clickTag: id => {
        const current = getPageItemById(id, menuData);
        setCurrentTag(current);
        //  点击已经打开的tab， 判断是否是新开的详情页面？ 是-把缓存的参数传递过去，否-直接跳转
        if (current.path?.indexOf('usualMonitor/AuditDetail') >= 0) {
          let selectRow = JSON.parse(window.localStorage.getItem('usualMonitorFlightNo')) || [];
          router.push({
            pathname: current.path,
            state: { selectRow },
          })
        } else if (current.path === '/compensation/indemnityForm') {
          let indemnityFormData = JSON.parse(window.localStorage.getItem('indemnityFormState')) || {};
          router.push({
            pathname: current.path,
            state: indemnityFormData,
          });
        } else if (current.path === '/compensation/CompensationAudit/AuditDetail') {
          let compensationAuditState = JSON.parse(window.localStorage.getItem('compensationAuditState')) || {};
          router.push({
            pathname: current.path,
            state: compensationAuditState,
          });
        } else if (current.path === '/compensation/luggageLndemnifyDetails') {
          let luggageLndemnifyDetailsState = JSON.parse(window.localStorage.getItem('luggageLndemnifyDetailsState')) || {};
          router.push({
            pathname: current.path,
            state: luggageLndemnifyDetailsState,
          });
        } else {
          router.push(current.path);
        };
      },
      onPathChange(path) {
        if (path === currentTag.path) return; // 解决关闭后重复添加
        // 防止异常行李事故单/旅客超售事故单 页内modal打开之后，其他页面无法滚动(if-避免不必要重排)
        if (['/compensation/oversaleindex', '/compensation/luggageindex', '/compensation/indemnityForm'].indexOf(path) > -1) {
          document.getElementsByTagName('body')[0].style.overflow = 'auto';
        };
        let current = {};
        if (doNotRoute.indexOf(path) > -1) {
          if (!currentTag.path) {
            router.push(sessionStorage.getItem('activeTag') || '/banksearchSystem/systemIndex')
            // router.goBack();
          }
          return;
        } else {
          current = getPageItemByPath(path, menuData);
        }
        if (currentTag.type === '1') {
          sessionStorage.setItem('activeTag', path);
        }
        // const current = getPageItemByPath(path, menuData);
        // 修改 航延补偿页面 的标题（第一次标题更改之后，就叫·新建【XXX】航延服务申请单·）
        if (current.name === '航延补偿页面' || current.name?.indexOf('】航延服务申请单') >= 0) {
          let flightInfo = JSON.parse(window.localStorage.getItem('usualMonitorFlightNo')) || [];
          current.name = `新建【${flightInfo[0]?.flightNumber}】航延服务申请单`;
          // 清除航延补偿页面的缓存
          dropScope(current.path);
        };
        // 修改 补偿单管理 双击查看补偿单详情页面的标题
        if (current.name?.indexOf('补偿详情') >= 0) {
          let indemnityFormData = JSON.parse(window.localStorage.getItem('indemnityFormState')) || {};
          current.name = indemnityFormData?.type === 'add' ?
            `修改【${indemnityFormData?.editInfo?.orderId}】补偿详情` :
            `查看【${indemnityFormData?.orderId}】补偿详情`;
        };
        // 修改 补偿单审核 双击查看补偿单审核的标题
        if (current.name === '补偿单审核详情' || current.name?.indexOf('】补偿单审核') >= 0) {
          let indemnityFormData = JSON.parse(window.localStorage.getItem('compensationAuditState')) || {};
          current.name = `【${indemnityFormData?.orderId}】补偿单审核`;
        };
        // 解除箱包补偿单详情的缓存
        if (current.name === '箱包补偿单详情' && current.path === '/compensation/luggageLndemnifyDetails') {
          dropScope(current.path);
        };
        if (current.path) {
          if (current.path === path || (current.containPath && ~current.containPath.split(';').indexOf(path))) {
            const subMenu = current.pid ? getParentMenuByPage(current, menuData) : {};
            setCurrentSubMenu(subMenu);
            const isInTags = tagOptions._isInTags(current.id, tags);
            if (!isInTags) {
              setTags(tags => tags.concat([current]));
            } else {
              // 如果跳转的目标页面 存在于 tags 数组中， 就更新tags中航延补偿的路由对象。 以便于tags的标题更新
              if (current.path?.indexOf('usualMonitor/AuditDetail') >= 0 ||
                current.path === '/compensation/indemnityForm' ||
                current.path === '/compensation/CompensationAudit/AuditDetail' ||
                current.path === '/compensation/luggageLndemnifyDetails') {
                let tempTags = JSON.parse(JSON.stringify(tags))
                for (let item of tempTags) {
                  if (item.id === current.id) {
                    item.name = current.name;
                  }
                };
                setTags(tempTags);
              };
            };
            setCurrentTag(current);
          } else {
            router.push(current.path); // 如果当前路径是菜单路径，跳转到页面路径
          }
        }
      },
      _isInTags: (id, tags) => ![].every.call(tags, item => item.id !== id),
    }),
    [tags, setTags, menuData, currentTag],
  );

  useEffect(() => {
    // 解除补偿单详情的缓存，避免点击不同的赔偿单数据不刷新的bug。
    dropScope('/compensation/indemnityForm');
    dropScope('/compensation/CompensationAudit/AuditDetail');
    for (let item of doNotRoute) {
      dropScope(item);
    }

    tagOptions.onPathChange(location.pathname);
  }, [location, tagOptions, dropScope]);

  const [collapsed, setCollapsed] = useState(false);
  const [startTest, setStartTest] = useState(false);

  return (
    <>
      <Tabs
        hideAdd
        onTabClick={tagOptions.clickTag}
        activeKey={currentTag.id}
        type={tags.length > 1 ? 'editable-card' : 'card'}
        onEdit={(target, action) => {
          action === 'remove' && tagOptions.removeTag(target, 'iconClose');
        }}
        className="rest-tabs-to-menu-tag"
      >
        {tags.map(pane => (
          <Tabs.TabPane tab={pane.name} key={pane.id} style={{ display: 'none' }}></Tabs.TabPane>
        ))}
      </Tabs>
      <KeepAlive id={children?.props?.location?.pathname} name={children?.props?.location?.pathname}>
        <div style={{ margin: '0px 16px' }}>{children}</div>
      </KeepAlive>
    </>
  );
};

export default connect(({ global, settings, auditDetail }) => ({
  collapsed: global.collapsed,
  settings,
  auditDetail
}))(SubNavLayout);
